package com.ctshk.sapp.scenic.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.mail.core.MailTemplate;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.web.support.BaseController;
import com.ctshk.rpc.scenic.dto.ApplyUserInfoDTO;
import com.ctshk.rpc.scenic.dto.RegistrationListExport;
import com.ctshk.rpc.scenic.dto.TicketLuckDrawApplyUserInfoDTO;
import com.ctshk.rpc.scenic.req.ApplyUserInfoReq;
import com.ctshk.rpc.scenic.req.RegistrationExportReq;
import com.ctshk.rpc.scenic.req.TicketLuckDrawApplyUserInfoReq;
import com.ctshk.rpc.scenic.service.ITicketLuckDrawApplyUserInfoService;
import com.ctshk.rpc.scenic.service.ITicketTypeLuckDrawService;
import com.ctshk.sapp.scenic.convert.LocalDateConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 门票抽奖用户报名信息表 前端控制器
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-02-18
 */
@Api(value = "冬奥会报名相关接口", tags = "冬奥会")
@RestController
@RequestMapping("/ticket-luck-draw-apply-user-info")
public class TicketLuckDrawApplyUserInfoController extends BaseController {

    @DubboReference
    private ITicketLuckDrawApplyUserInfoService userInfoService;

    @DubboReference
    private ITicketTypeLuckDrawService drawService;

    @Autowired
    private MailTemplate mailTemplate;


    /**
     * 根据查询编号，电话，是否同意降级，上架状态查询出：
     * 查询编号，申请人信息（姓名，电话，同意，选择场次），门票数 和报名日期
     *
     * @param applyUserInfoReq
     */
    @ApiOperation(value = "查询报名信息列表", notes = "查询报名信息列表")
    @PostMapping("/FindApplyUser")
    public Result<PageResponse<ApplyUserInfoDTO>> FindApplyUser(@RequestBody ApplyUserInfoReq applyUserInfoReq) {

        return userInfoService.FindApplyUser(applyUserInfoReq);
    }

    /**
     * 点击详情
     * 根据查询编号查询申请人详情
     *
     * @param queryNumber
     * @return
     */
    @ApiOperation(value = "根据查询编号查询申请人详情", notes = "根据查询编号查询申请人详情")
    @GetMapping("/UserDetailByNumber/{queryNumber}")
    public Result<TicketLuckDrawApplyUserInfoDTO> userDetailByNumber(@PathVariable String queryNumber) {
        return Result.success(userInfoService.userDetailByNumber(queryNumber));
    }

    /**
     * 修改申请人资料
     *
     * @param ticketUserInfoReq
     * @return
     */
    @ApiOperation(value = "修改申请人资料", notes = "修改申请人资料")
    @PostMapping("/editUserInfo")
    public Result editUserInfo(@RequestBody TicketLuckDrawApplyUserInfoReq ticketUserInfoReq) {
        //最多只能添加四个种类的门票
        if (ticketUserInfoReq.getTickets().size() > 4) {
            return Result.failed(SystemError.SEASON_TICKET_20026);
        }
        return userInfoService.editUserInfo(ticketUserInfoReq);
    }
    /**
     * 发送中签通知
     *
     * @param
     * @return
     */
    @ApiOperation(value = "发送中签通知", notes = "发送中签通知")
    @GetMapping("/sendNotice")
    public Result sendNotice(
            @NotBlank(message = "请输入通知类型")
            @ApiParam("通知类型1=邮件,2=短信") Integer type,
            @NotBlank(message = "请输入通知地址")
            @ApiParam("通知地址:手机号/邮箱号") String to,
            @NotBlank(message = "请输入通知内容")
            @ApiParam("通知内容") String content) {
        if (1 == type) {
            mailTemplate.sendSimpleMail(to, "中签通知", content);
        }
        if (2 == type) {
            //TODO 待短信接口开发完成再接入
        }

        return Result.success();
    }

    /**
     * 报名清单导出
     */
    @ApiOperation(value = "报名名单导出(支持根据根据条件导出)", notes = "报名名单导出")
    @PostMapping("/registration-export")
    public void registrationListExport(@RequestBody RegistrationExportReq req, HttpServletResponse response) {
        try {
            List<ApplyUserInfoDTO> applyUsers = userInfoService.registrationListExport(req);
            List<RegistrationListExport> exports = new ArrayList<>();
            applyUsers.forEach(applyUserInfoDTO -> {
                RegistrationListExport export = new RegistrationListExport();
                BeanUtils.copyProperties(applyUserInfoDTO, export);
                if (null != applyUserInfoDTO.getAgree()) {
                    if (1 == applyUserInfoDTO.getAgree()) {
                        export.setAgreeStr("是");
                    } else {
                        export.setAgreeStr("否");
                    }
                } else {
                    export.setAgreeStr("否");
                }
                exports.add(export);
            });
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("冬奥会报名清单", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //样式
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            //导出
            EasyExcel.write(response.getOutputStream(), RegistrationListExport.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("报名清单").registerConverter(new LocalDateConverter()).doWrite(exports);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(SystemError.SYS_500);
        }
    }

    /**
     * 抽签
     *
     * @param
     * @return
     */
    @ApiOperation(value = "门票抽签", notes = "门票抽签")
    @GetMapping("/draw")
    public Result drawTicket(HttpServletRequest request) {
        return drawService.drawTicket(getCurrentUser(request).getId());
    }
}
